# coding=utf-8
from flask import render_template, request, session, flash, url_for, redirect, abort

from config import app
from models import Bookmark, Tag


def login_require():
    if not session.get('logged_in', False):
        return redirect(url_for('login'))


@app.route('/')
@app.route('/tag/<tag>')
def show_bookmarks(tag=None):
    if tag:
        tag = Tag.query.filter_by(name=tag).first_or_404()
        bookmarks = tag.bookmarks
    else:
        bookmarks = Bookmark.query.order_by('id DESC').all()

    tags = Tag.query.all()
    return render_template('bookmarks.html', bookmarks=bookmarks, tags=tags)


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = u'无效的用户名'
        elif request.form['password'] != app.config['PASSWORD']:
            error = u'无效的密码'
        else:
            session['logged_in'] = True
            flash(u'登录成功')
            return redirect(url_for('show_bookmarks'))
    return render_template('login.html', error=error)


@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash(u'您已经退出')
    return redirect(url_for('login'))


@app.route('/add', methods=['POST', 'GET'])
def add_bookmark():
    if not session.get('logged_in', False):
        return redirect(url_for('login'))

    error = None
    bookmark = Bookmark()
    bookmark.title = ''
    bookmark.url = ''

    if request.method == 'POST':
        title = request.form['title'].strip()
        url = request.form['url'].strip()
        tag_names = request.form['tags'].strip()
        if not title:
            error = u'标题不能为空'
        elif not url:
            error = u'Url不能为空'

        if url and not url.startswith('http://'):
            error = u'Url无效'

        if url and Bookmark.url_exists(url):
            error = u'Url已存在'

        bookmark.title = title
        bookmark.url = url
        bookmark.tag_names = tag_names

        if not error:
            bookmark.save()
            flash(u'添加成功')
            return redirect(url_for('show_bookmarks'))

    return render_template('add_bookmark.html', error=error, bookmark=bookmark)


@app.route('/edit/<int:bm_id>', methods=['POST', 'GET', 'PUT'])
def edit_bookmark(bm_id):
    if not session.get('logged_in', False):
        return redirect(url_for('login'))

    bookmark = Bookmark.query.filter_by(id=bm_id).first()
    if bookmark is None:
        return abort(404)

    error = None
    if request.method == 'POST':
        title = request.form['title'].strip()
        url = request.form['url'].strip()
        tag_names = request.form['tags'].strip()
        if not title:
            error = u'标题不能为空'
        elif not url:
            error = u'Url不能为空'

        if url and not url.startswith('http://'):
            error = u'Url无效'

        if url and url != bookmark.url and Bookmark.url_exists(url):
            error = u'Url已存在'

        bookmark.title = title
        bookmark.url = url
        bookmark.tag_names = tag_names

        if not error:
            bookmark.save()
            flash(u'保存成功')
            return redirect(url_for('edit_bookmark', bm_id=bm_id))

    return render_template('edit_bookmark.html', bookmark=bookmark, error=error)


@app.route('/delete/<int:bm_id>', methods=['POST', 'DELETE'])
def delete_bookmark(bm_id):
    if not session.get('logged_in', False):
        return abort(401)

    bookmark = Bookmark.query.filter_by(id=bm_id).first_or_404()
    bookmark.delete()
    return 'success'


@app.route('/tag/delete/<int:tag_id>', methods=['POST', 'DELETE'])
def delete_tag(tag_id):
    if not session.get('logged_in', False):
        return abort(401)

    tag = Tag.query.filter_by(id=tag_id).first_or_404()
    tag.delete()
    return 'success'


@app.route('/tag/<int:tag_id>/rename', methods=['POST'])
def rename_tag(tag_id):
    if not session.get('logged_in', False):
        return abort(401)

    tag = Tag.query.filter_by(id=tag_id).first_or_404()
    tag.name = request.form['name']
    tag.save()
    return 'success'


if __name__ == '__main__':
    app.run()
